<template>
  <t-drawer
    :title="title"
    placement="right"
    :width="640"
    :visible="visible"
    :destroyOnClose="true"
    @close="
      () => {
        $emit('cancel');
      }
    "
    wrapClassName="custom-drawer-container"
  >
    <div class="custom-drawer-container">
      <div class="table-tool">
        <template v-if="type != 'user'">
          <a-button
            class="cu-btn-primary"
            icon="plus"
            @click="handleAccess('all')"
          >
            {{ $ct("batchLicensing", "批量授权") }}
          </a-button>
          <a-button
            :disabled="roleUuid == '402888e5575f3ab7015760002082076e'"
            :class="
              roleUuid !== '402888e5575f3ab7015760002082076e'
                ? 'cu-btn-danger'
                : ''
            "
            type="link"
            @click="handleAccess('all', 'cancellation')"
          >
            {{ $ct("batchCancel", "批量取消") }}
          </a-button>
        </template>
        <template v-else>
          <a-button class="cu-btn-primary" icon="plus" @click="addUser">
            添加用户
          </a-button>
        </template>
      </div>
      <div class="table-content">
        <vxe-table
          ref="xTable"
          height="99%"
          align="center"
          border="inner"
          :data="tableData"
          :column-config="{ resizable: false }"
          size="small"
          :scroll-y="{ enabled: true }"
          :scroll-x="{ enabled: true }"
          :tree-config="{
            rowField: 'id',
            parentField: 'pid',
            childrenField: 'children',
            expandAll: true,
            iconOpen: 'vxe-icon-square-minus',
            iconClose: 'vxe-icon-square-plus',
          }"
          :row-config="{ keyField: 'id' }"
          @checkbox-all="selectAllEvent"
          @checkbox-change="selectChangeEvent"
        >
          <vxe-table-column type="checkbox" width="60"></vxe-table-column>
          <!--  -->
          <vxe-column
            field="menuName"
            title="菜单名称"
            align="left"
            tree-node
            v-if="type != 'user'"
          >
          </vxe-column>
          <vxe-column field="access" title="授权状态" v-if="type != 'user'">
            <template #default="{ row }">
              {{ row.access | accessFilter(type) }}
            </template>
          </vxe-column>
          <!--  -->
          <vxe-column
            field="userHeadPortrait"
            title="头像"
            v-if="type == 'user'"
          >
            <template #default="{ row }">
              <img :src="row.text" alt="" class="business-license" />
            </template>
          </vxe-column>
          <vxe-column
            field="userName"
            title="菜单名称"
            v-if="type == 'user'"
          ></vxe-column>
          <vxe-column
            field="userNameId"
            title="用户账号"
            v-if="type == 'user'"
          ></vxe-column>
          <vxe-column
            field="orgName"
            title="所属组织"
            v-if="type == 'user'"
          ></vxe-column>
          <!--  -->
          <vxe-column field="operate" width="100" title="操作" fixed="right">
            <template #default="{ row }">
              <template v-if="type != 'user'">
                <template
                  v-if="
                    !~['TabsView', 'PageView', 'RouteView', null].indexOf(
                      row.menuAssembly
                    )
                  "
                >
                </template>
              </template>
              <span class="action-margin"></span>
              <template v-if="type != 'user'">
                <a v-if="row.access != 1" @click="handleAccess(row)">
                  {{ $ct("toGrantAuthorization", "授权") }}
                </a>
                <a
                  v-else
                  :disabled="roleUuid == '402888e5575f3ab7015760002082076e'"
                  :class="
                    roleUuid !== '402888e5575f3ab7015760002082076e'
                      ? 'action-delete'
                      : ''
                  "
                  @click="handleAccess(row, 'cancellation')"
                >
                  {{ $ct("cancelAuth", "取消授权") }}
                </a>
              </template>
              <template v-else>
                <a-popconfirm
                  title="确认要取消授权吗?"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="removeUser(record)"
                >
                  <a class="action-delete">移除</a>
                </a-popconfirm>
              </template>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <div class="table-pager" v-if="type == 'user'">
        <vxe-pager
          size="small"
          background
          :current-page.sync="pager.page"
          :page-size.sync="pager.pageSize"
          :total="pager.total"
          :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes']"
          :page-sizes="[20, 50, 100, 500]"
          @page-change="paginationChange"
        >
          <template #left>
            <div class="vxe-pager-left-tip-container">
              共<span>{{ pager.total }}</span
              >条
            </div>
          </template>
        </vxe-pager>
      </div>
    </div>
    <div class="ant-drawer-footer">
      <a-button
        :style="{ marginRight: '8px' }"
        @click="
          () => {
            $emit('cancel');
          }
        "
      >
        取消
      </a-button>
    </div>
    <data-auth-list
      ref="dataAuthList"
      :visible="dataAuthListVisible"
      :model="dataAuthListModel"
      @ok="dataAuthListOk"
      @cancel="dataAuthListCancel"
    />
    <list-auth-list
      ref="listAuthList"
      :visible="listAuthListVisible"
      :model="listAuthListModel"
      @ok="listAuthListOk"
      @cancel="listAuthListCancel"
    />
    <form-auth-list
      ref="formAuthList"
      :visible="formAuthListVisible"
      :model="formAuthListModel"
      @ok="formAuthListOk"
      @cancel="formAuthListCancel"
    />
    <personnel-popup
      ref="PersonnelPopup"
      @change="getNewUser"
      :multiple="true"
      :whetherShow="false"
    />
  </t-drawer>
</template>

<script>
import { getFilter } from "@/utils/TopVUI";
import dataAuthList from "./dataAuthList.vue";
import listAuthList from "./listAuthList.vue";
import formAuthList from "./formAuthList.vue";
import { PersonnelPopup } from "@/components";
export default {
  components: {
    dataAuthList,
    listAuthList,
    formAuthList,
    PersonnelPopup,
  },
  props: {
    visible: {
      type: Boolean,
      default: () => false,
    },
  },
  data() {
    return {
      title: "",
      loadingText: "",
      loading: false,
      type: "",
      roleId: "",
      roleUuid: "",
      rowData: {},
      queryParam: {},
      dataAuthListVisible: false,
      listAuthListVisible: false,
      formAuthListVisible: false,
      dataAuthListModel: null,
      listAuthListModel: null,
      formAuthListModel: null,
      //列表
      loading: false,
      tableData: [],
      pager: {
        page: 1,
        pageSize: 20,
        total: 0,
      },
      selectedRowKeys: [],
    };
  },
  filters: {
    accessFilter(val, type) {
      let txt = "";
      if (val === 1 || val === "1") {
        txt = "已授权";
      } else if (val === 0) {
        txt = "未授权";
      } else if (type === "data" && !val) {
        txt = "";
      } else {
        txt = "未授权";
      }
      return txt;
    },
  },
  methods: {
    //监听table全选
    selectAllEvent({ checked, records }) {
      if (checked) {
        this.selectedRowKeys = records.map((v) => v.id);
        this.selectedRowKeys = [...new Set(this.selectedRowKeys)];
      } else {
        this.tableCheckRecords = [];
      }
    },

    //监听table复选框
    selectChangeEvent({ checked, records, row }) {
      let { id } = row;
      if (checked) {
        this.selectedRowKeys = records.map((v) => v.id);
        this.selectedRowKeys = [...new Set(this.selectedRowKeys)];
      } else {
        this.selectedRowKeys = this.selectedRowKeys.filter((v) => v != id);
      }
    },

    getList(data, type) {
      this.type = type;
      this.roleId = data.id;
      this.roleUuid = data.uuid;
      let url = "";
      let listStr = "";
      if (type === "web") {
        url = "/system/authAccess/getListAccessWebMenuByRoleId";
        listStr = "SysButtonList";
      } else if (type === "app") {
        url = "/system/authAccess/getListAccessAppMenuByRoleId";
        listStr = "SysAppMenuList";
      } else if (type === "user") {
        url = "/mdata/user/getPageSetUserByRoleId";
        listStr = "rows";
        this.queryParam.pageSize = this.pager.pageSize;
        this.queryParam.pageNo = this.pager.page;
        this.queryParam.id = this.roleId;
      } else if (type === "data") {
        url = "/system/sysDataAuth/getListByPid";
        this.queryParam.roleType = "menu";
      }
      this.rowData = data;
      this.queryParam.roleId = data.id;
      this.$post(url, this.queryParam)
        .then((res) => {
          let data = res.data;
          if (res.statusCode === 200) {
            if (this.type === "user") {
              this.pager.total = data.totalCount;
            }
            if (this.type === "data") {
              let sourceData = [];
              let children = [];
              data.forEach((e) => {
                if (e.pid == 1) {
                  e.key = e.id;
                  e.children = e.state === "closed" ? [] : "";
                  sourceData.push(e);
                } else {
                  children.push(e);
                }
              });
              data = getFilter(sourceData, children);
            }
            this.tableData = listStr ? data[listStr] : data;
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },

    handleAccess(e, type) {
      let key = this.selectedRowKeys;
      let url = "";
      if (e === "all") {
        if (this.selectedRowKeys.length === 0) {
          this.$message.warn("请先选择需要操作的数据");
          return;
        }
      } else {
        key = [e.id];
      }
      this.loading = true;
      this.loadingText = "授权中...";
      let params = {
        roleId: this.rowData.id,
        menuId: JSON.stringify(key),
        type: type,
      };
      if (this.type === "web") {
        url = "/system/authAccess/authorize";
      } else if (this.type === "app") {
        url = "/system/authAccess/appAuthorize";
      } else if (this.type === "data") {
        if (type === "cancellation") {
          url = "/system/sysDataAuth/cancelRule";
        } else {
          url = "/system/sysDataAuth/addRule";
        }
        params = {
          roleId: this.rowData.id,
          uuid: key.toString(),
        };
      }
      this.$post(url, params).then((res) => {
        if (res.statusCode === 200) {
          this.getList(this.rowData, this.type);
          this.$message.success(res.message, 1.5);
        } else {
          this.$message.error(res.message, 1.5);
        }
      });
    },

    dataAuth(menuId) {
      this.dataAuthListVisible = true;
      this.$refs.dataAuthList.loadData(menuId, this.queryParam.roleId);
    },
    listAuth(menuId) {
      this.listAuthListVisible = true;
      this.$refs.listAuthList.loadData(menuId, this.queryParam.roleId);
    },
    formAuth(menuId) {
      this.formAuthListVisible = true;
      this.$refs.formAuthList.loadData(menuId, this.queryParam.roleId);
    },
    dataAuthListOk() {
      this.dataAuthListVisible = false;
    },
    listAuthListOk() {
      this.listAuthListVisible = false;
    },
    formAuthListOk() {
      this.formAuthListVisible = false;
    },
    dataAuthListCancel() {
      this.dataAuthListVisible = false;
    },
    listAuthListCancel() {
      this.listAuthListVisible = false;
    },
    formAuthListCancel() {
      this.formAuthListVisible = false;
    },
    addUser() {
      this.$refs.PersonnelPopup.openModal();
    },
    getNewUser(data) {
      this.$post("/mdata/user/cancelOraddUserRole", {
        roleId: this.roleId,
        userNameId: data,
        type: "add",
      }).then((res) => {
        if (res.statusCode === 200) {
          this.$message.success("添加用户成功");
          this.getList(this.rowData, this.type);
        } else {
          this.$message.error(res.message);
        }
      });
    },
    removeUser(record) {
      this.$post("/mdata/user/cancelOraddUserRole", {
        roleId: this.roleId,
        userNameId: record.userNameId,
        type: "cancel",
      }).then((res) => {
        if (res.statusCode === 200) {
          this.$message.success("取消授权成功");
          this.getList(this.rowData, this.type);
        } else {
          this.$message.error(res.message);
        }
      });
    },

    //监听分页切换
    paginationChange({ currentPage, pageSize }) {
      this.pager.page = currentPage;
      this.pager.pageSize = pageSize;
      this.getList(this.rowData, this.type);
    },

    onClose() {
      this.$emit("cancel");
    },
  },
  beforeDestroy() {},
};
</script>

<style lang="less" scoped>
/deep/.ant-drawer-body {
  height: calc(100% - 55px);
  padding: 0;
  display: flex;
  flex-direction: column;
  .custom-drawer-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    .table-tool {
      padding: 8px 5px;
      box-sizing: border-box;
      flex-shrink: 0;
    }
    .table-content {
      flex: 1;
    }
    .table-pager {
      flex-shrink: 0;
    }
  }
  .ant-drawer-footer {
    display: flex;
    justify-content: flex-end;
    padding: 10px 16px;
    box-sizing: border-box;
    border-top: 1px solid rgb(233, 233, 233);
  }
}
</style>
